<template>
  <div class="order-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-wrapper">
      <el-icon class="is-loading" :size="40"><Loading /></el-icon>
      <p>正在加载订单详情...</p>
    </div>

    <!-- 错误状态 -->
    <el-result 
      v-else-if="error" 
      icon="error" 
      title="加载失败"
      :sub-title="errorMessage"
    >
      <template #extra>
        <el-button type="primary" @click="retryLoad">重试</el-button>
      </template>
    </el-result>

    <!-- 订单详情 -->
    <el-card v-else class="order-card">
      <template #header>
        <div class="card-header">
          <h2>订单详情</h2> 
          <el-tag :type="getStatusTagType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </div>
      </template>

      <!-- 基础信息 -->
      <div class="order-info">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ currentOrder.orderNumber }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间：</span>
          <span class="value">{{ formatTime(currentOrder.createdAt) }}</span>
        </div>
      </div>

      <!-- 商品信息 -->
      <el-divider content-position="left">商品信息</el-divider>
      <div class="product-info">
        <el-image 
          :src="'http://localhost:8092' + currentOrder.images" 
          fit="cover" 
          class="product-image"
          :preview-src-list="['http://localhost:8092' + currentOrder.images]"
        >
          <template #error>
            <div class="image-error">图片加载失败</div>
          </template>
        </el-image>
        
        <div class="product-detail">
          <h3 class="product-name">{{ currentOrder.productName }}</h3>
          <div class="price-info">
            <span class="label">单价：</span>
            <span class="value">¥{{ currentOrder.price }}</span>
          </div>
          <div class="quantity-info">
            <span class="label">数量：</span>
            <span class="value">x{{ currentOrder.quantity }}</span>
          </div>
          <div class="total-price">
            <span class="label">总价：</span>
            <span class="value">¥{{ currentOrder.totalAmount }}</span>
          </div>
        </div>
      </div>

      <!-- 其他信息 -->
      <el-divider content-position="left">订单信息</el-divider>
      <div class="additional-info">
        <div class="info-row">
          <span class="label">支付方式：</span>
          <span class="value">{{ currentOrder.paymentMethod || '暂无' }}</span>
        </div>
        <div class="info-row">
          <span class="label">最后更新：</span>
          <span class="value">{{ formatTime(currentOrder.updatedAt) }}</span>
        </div>
      </div>

      <!-- 新增操作按钮 -->
      <el-divider content-position="left">订单操作</el-divider>
      <div class="action-buttons">
        <!-- <el-button 
          type="primary" 
          @click="handleContactSeller"
          class="action-btn"
        >
          联系卖家
        </el-button>
        <el-button 
          type="info" 
          @click="handleAfterSales"
          class="action-btn"
        >
          售后服务
        </el-button> -->
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

const route = useRoute()
const orderNumber = ref('')
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const orderData = ref([])
const orderId = ref('')
// 状态映射
const statusMap = {
  1: { text: '待支付', type: 'warning' },
  2: { text: '已支付', type: 'success' },
  3: { text: '已发货', type: '' },
  4: { text: '已完成', type: 'info' },
  5: { text: '已取消', type: 'danger' }
}

// 获取当前订单（取第一条）
const currentOrder = computed(() => {
  return orderData.value || {
    productName: '未知商品',
    price: '0.00',
    quantity: 0,
    totalAmount: '0.00',
    status: 1,
    paymentMethod: ''
  }
})

// 方法
const getStatusText = (status) => {
  return statusMap[status]?.text || '未知状态'
}

const getStatusTagType = (status) => {
  return statusMap[status]?.type || 'info'
}

const formatTime = (timestamp) => {
  if (!timestamp) return '未知时间'
  try {
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', { 
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    return '时间格式错误'
  }
}

const fetchOrderDetail = async () => {
  try {
    loading.value = true
    error.value = false
    
    const response = await axios.get('http://localhost:8092/order/getOrderDetail', {
      params: { orderId: orderId.value }
    })

    if (response.data.code === 200 && response.data.data?.length > 0) {
      orderData.value = response.data.data[0]
      orderData.value.images = orderData.value.images
    } else {
      throw new Error(response.data.msg || '订单不存在')
    }
  } catch (err) {
    error.value = true
    errorMessage.value = err.response?.data?.msg || err.message
    ElMessage.error(`加载失败: ${errorMessage.value}`)
  } finally {
    loading.value = false
  }
}

const retryLoad = () => {
  error.value = false
  fetchOrderDetail()
}

// 新增按钮处理方法
const handleContactSeller = () => {
  console.log('联系卖家操作', {
    orderNumber: currentOrder.value.orderNumber,
    sellerId: currentOrder.value.sellerId
  })
}

const handleAfterSales = () => {
  console.log('售后服务操作', {
    orderNumber: currentOrder.value.orderNumber,
    productId: currentOrder.value.productId
  })
}

onMounted(() => {
  orderId.value = route.params.orderId || route.query.orderId
  if (orderId.value) {
    fetchOrderDetail()
  } else {
    error.value = true
    errorMessage.value = '缺少订单号参数'
    loading.value = false
  }
})
</script>

<style scoped>
.order-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.loading-wrapper {
  text-align: center;
  padding: 40px;
  color: #666;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.order-info {
  margin-bottom: 30px;
  padding: 0 20px;
}

.info-item {
  margin: 10px 0;
  font-size: 14px;
}

.product-info {
  display: flex;
  gap: 30px;
  padding: 0 20px;
}

.product-image {
  width: 300px;
  height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.product-detail {
  flex: 1;
}

.product-name {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.price-info, .quantity-info, .total-price {
  margin: 15px 0;
  font-size: 16px;
}

.total-price {
  color: #e4393c;
  font-size: 18px;
  font-weight: bold;
}

.label {
  color: #999;
  margin-right: 8px;
}

.value {
  color: #333;
}

.additional-info {
  padding: 0 20px;
}

.image-error {
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.el-divider {
  margin: 30px 0;
}

/* 新增按钮样式 */
.action-buttons {
  margin-top: 30px;
  padding: 0 20px;
  display: flex;
  justify-content: flex-end;
  gap: 20px;
}

.action-btn {
  min-width: 120px;
  padding: 12px 24px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>